<template>
	<view class="scan">
		<c-section title="设备列表"></c-section>
		<view class="wrapper">
			<scroll-view :scroll-y="true" :style="{height: (systemInfo.scrollHeight-80)+'px'}">
				<c-list :dataArr="devices||[]" @click="handleClick"></c-list>
			</scroll-view>
		</view>
		<view class="operate">
			<button class="btn" type="default" :disabled="!scanning" @click="handleStop">
				停止扫描
			</button>
			<button class="btn" type="default" :disabled="scanning" :loading="scanning" @click="handleStart">
				开始扫描
			</button>
		</view>
	</view>
</template>

<script>
	import {
		mapGetters,
		mapMutations
	} from 'vuex';
	// #ifdef APP-PLUS
	import mixBluetooth from '../../mixins/bluetooth-plus.js';
	// #endif
	// #ifndef APP-PLUS
	import mixBluetooth from '../../mixins/bluetooth.js';
	// #endif
	import mixDevice from '../../mixins/device.js';

	export default {
		mixins: [mixBluetooth, mixDevice],
		computed: {
			scanning() {
				return this.$store.state.adapter.status === 3;
			},
			devices() {
				return this.$store.state.device.scanneds;
			},
			...mapGetters('system', ['systemInfo'])
		},
		methods: {
			handleStart() {
				this.startDiscovery();
			},
			handleStop() {
				this.stopDiscovery();
			},
			handleClick(device) {
				const that = this;

				const deviceId = that.checkConnected(false);
				if (deviceId) {
					if (deviceId === device.id) {
						uni.navigateTo({
							url: '../detail/detail'
						});
					} else {
						uni.showToast({
							title: '已连接其他设备',
							icon: 'error'
						});
					}
					return;
				}

				uni.showModal({
					title: '系统提示',
					content: '连接设备[' + device.name + ']?',
					success(res) {
						if (res.confirm) {
							that.createConnection(device, () => {
								uni.navigateTo({
									url: '../detail/detail'
								});
							});
						}
					}
				});
			},
			...mapMutations('device', ['addScanned', 'addHistory', 'clearScanned']),
			...mapMutations('log', ['addOprLog'])
		}
	}
</script>

<style lang="scss">
	.scan {
		.wrapper {
			padding: 0 20rpx;
		}

		.operate {
			display: flex;
			position: absolute;
			width: 100%;
			bottom: 50rpx;

			.btn {
				flex: 1;
				margin: 0 50rpx;
				display: flex;
				justify-content: center;
				align-items: center;
			}
		}
	}
</style>
